//
//  WorksetUploadManager.m
//  dataGathering
//
//  Created by macmini on 15/1/30.
//  Copyright (c) 2015年 shuili. All rights reserved.
//

#import "WorksetUploadManager.h"

@interface WorksetUploadManager()
@property (nonatomic, strong) AFHTTPRequestOperationManager *uploadDBInfoManager;
@property (nonatomic, strong) AFHTTPRequestOperationManager *uploadMediaManager;

@property (nonatomic, strong) AFHTTPRequestOperationManager *downloadDBInfoManager;
@property (nonatomic, strong) AFHTTPRequestOperationManager *downloadMediaManager;

@property (nonatomic, strong) AFHTTPRequestOperationManager *downloadFeatueFileManager;

@property (nonatomic, strong) NSMutableArray *autoSyncWorksetList;
@property (nonatomic, strong) __block NSMutableArray *laytestWorksetJsonObjectArray;

@property (nonatomic, strong) NSOperationQueue *autoSyncOperationQueue;
@property (nonatomic, strong) dispatch_queue_t queue;
@end

@implementation WorksetUploadManager

static WorksetUploadManager *sharedManager=nil;

-(id)init
{
    self = [super init];
    if (self) {
        _uploadDBInfoManager = [AFHTTPRequestOperationManager manager];
        _uploadDBInfoManager.responseSerializer = [AFJSONResponseSerializer serializer];
        _uploadDBInfoManager.requestSerializer = [AFHTTPRequestSerializer serializer];
        [_uploadDBInfoManager.requestSerializer setValue:@"multipart/form-data" forHTTPHeaderField:@"Content-Type"];
        
        _uploadMediaManager = [AFHTTPRequestOperationManager manager];
        _uploadMediaManager.responseSerializer = [AFHTTPResponseSerializer serializer];
        _uploadMediaManager.requestSerializer = [AFHTTPRequestSerializer serializer];
        _uploadMediaManager.responseSerializer.acceptableContentTypes = [_uploadMediaManager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];
        [_uploadMediaManager.requestSerializer setValue:@"multipart/form-data" forHTTPHeaderField:@"Content-Type"];
        
        _downloadDBInfoManager = [AFHTTPRequestOperationManager manager];
        _downloadDBInfoManager.responseSerializer = [AFHTTPResponseSerializer serializer];
        _downloadDBInfoManager.requestSerializer = [AFJSONRequestSerializer serializer];
        [_downloadDBInfoManager.requestSerializer setValue:@"application/json;charset=utf-8" forHTTPHeaderField:@"Content-Type"];
        
        _downloadMediaManager = [AFHTTPRequestOperationManager manager];
        _downloadMediaManager.responseSerializer = [AFHTTPResponseSerializer serializer];
        _downloadMediaManager.requestSerializer = [AFJSONRequestSerializer serializer];
        [_downloadMediaManager.requestSerializer setValue:@"application/json;charset=utf-8" forHTTPHeaderField:@"Content-Type"];
        
        _autoSyncWorksetList = [[NSMutableArray alloc] initWithCapacity:10];
        
        _autoSyncOperationQueue = [[NSOperationQueue alloc] init];
        [_autoSyncOperationQueue setMaxConcurrentOperationCount:1];
        _queue = dispatch_queue_create("autoSync.queue", DISPATCH_QUEUE_SERIAL);
    }
    return self;
}

+(WorksetUploadManager *)sharedInstance{
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        sharedManager=[[WorksetUploadManager alloc] init];
        
    });
    return sharedManager;
}

- (NSString*)localDateToUploadDateString :(NSString*)dateString
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *localUpdateDate = [dateFormatter dateFromString:dateString];
    
    [dateFormatter setDateFormat:@"yyyyMMddHHmmss"];
    NSString *tranlateeString = [dateFormatter stringFromDate:localUpdateDate];
    return [tranlateeString mutableCopy];
}

- (void)newSyncAllWorksets
{
    [SVProgressHUD showWithStatus:@"获取服务器信息中..." maskType:SVProgressHUDMaskTypeBlack];
    
    [_laytestWorksetJsonObjectArray removeAllObjects];
    _laytestWorksetJsonObjectArray= [[NSMutableArray alloc] initWithCapacity:10];
    
    __block NSMutableArray *toUploadWorksetArray = [[NSMutableArray alloc] initWithCapacity:10];
    __block NSMutableArray *toDownloadWorksetArray = [[NSMutableArray alloc] initWithCapacity:10];
    
    NSDictionary *getLatestWorksetListParam = @{@"user":[[NSUserDefaults standardUserDefaults] objectForKey:@"username"]};
    
    AFHTTPRequestOperationManager *worksetListRequestManager = [AFHTTPRequestOperationManager manager];
    worksetListRequestManager.responseSerializer = [AFJSONResponseSerializer serializer];
    worksetListRequestManager.requestSerializer = [AFJSONRequestSerializer serializer];
    
    
    [worksetListRequestManager GET:ROOT_URL@"mobile/workset/getList" parameters:getLatestWorksetListParam success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"get workset list response is %@",responseObject);
        
        NSString *requestTmp = [NSString stringWithString:operation.responseString];
        NSData *resData = [[NSData alloc] initWithData:[requestTmp dataUsingEncoding:NSUTF8StringEncoding]];
        NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:resData options:NSJSONReadingMutableLeaves error:nil];
        
        NSNumber *getLayernumber = [resultDic objectForKey:@"success"];
        
        if([getLayernumber boolValue]){
            
            NSArray *latestWorksetArray = [resultDic objectForKey:@"result"];
            for(NSDictionary *dict in latestWorksetArray){
                NSError *error;
                WorksetModel *latestWorksetModel = [[WorksetModel alloc] initWithDictionary:dict error:&error];
                
                NSLog(@"json parse error is %@",error);
                [_laytestWorksetJsonObjectArray addObject:latestWorksetModel];
            }
            NSString *notiString = [NSString stringWithFormat:@"同步中..."];
            [SVProgressHUD setStatus:notiString];
            
            /*STEP 1. Check if new added or updated worksets need to upload*/
            for(workSet *localWorkset in [[currentWorkSetManager sharedInstance] getWorksetArray]){
                BOOL needUpdate = YES;
                for(WorksetModel *workset in _laytestWorksetJsonObjectArray){
                    if([[localWorkset name] isEqualToString:[workset name]]){
                        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
                        [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
                        NSDateFormatter *remoteDateFormatter = [[NSDateFormatter alloc] init];
                        [remoteDateFormatter setDateFormat:@"yyyyMMddHHmmss"];
                        NSDate *localUpdateDate = [dateFormatter dateFromString:[localWorkset updateTime]];
                        NSDate *remoteUpdateDate = [remoteDateFormatter dateFromString:[workset time_update]];
                        if([localUpdateDate isEqualToDate:remoteUpdateDate] || [[remoteUpdateDate laterDate:localUpdateDate] isEqualToDate:remoteUpdateDate]){
                            /*Deleting workset operation will be performed in upload process, just insert the to-be-deleted workset here*/
                            if(![localWorkset isDeleted]){
                                needUpdate = NO;
                            }
                        }
                    }
                }
                if(needUpdate){
                    [toUploadWorksetArray addObject:localWorkset];
                }
            }
            
            /*STEP 2. Check if new added or updated worksets need to download*/
            
            for(WorksetModel *workset in _laytestWorksetJsonObjectArray){
                BOOL needDownload = YES;
                for(workSet *localWorkset in [[currentWorkSetManager sharedInstance] getWorksetArray]){
                    if([[localWorkset name] isEqualToString:[workset name]]){
                        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
                        [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
                        NSDateFormatter *remoteDateFormatter = [[NSDateFormatter alloc] init];
                        [remoteDateFormatter setDateFormat:@"yyyyMMddHHmmss"];
                        NSDate *localUpdateDate = [dateFormatter dateFromString:[localWorkset updateTime]];
                        NSDate *remoteUpdateDate = [remoteDateFormatter dateFromString:[workset time_update]];
                        if([localUpdateDate isEqualToDate:remoteUpdateDate] || [[remoteUpdateDate laterDate:localUpdateDate] isEqualToDate:localUpdateDate]){
                            needDownload = NO;
                        }
                    }
                    
                }
                if(needDownload){
                    [toDownloadWorksetArray addObject:workset];
                }
            }
            if([toUploadWorksetArray count] > 0){
                [self beginUploadTasks:toUploadWorksetArray: toDownloadWorksetArray];
            } else {
                [self beginDownloadTask:toDownloadWorksetArray];
            }
            [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(newCheckingAllOperationFinished:) userInfo:nil repeats:YES];
            
            //[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(checkingUploadOperationAllFinished:) userInfo:_laytestWorksetJsonObjectArray repeats:YES];
            
            
        } else {
            [SVProgressHUD dismiss];
            [SVProgressHUD showErrorWithStatus:@"获取信息失败，请检查网络连接"];
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"get workset list error is %@",error);
        [SVProgressHUD dismiss];
        [SVProgressHUD showErrorWithStatus:@"获取信息失败，请检查网络连接"];
    }];

}

-(void)beginUploadTasks :(NSArray*)toUploadWorksetArray :(NSArray*)toDownloadArray
{
    if([toUploadWorksetArray count] == 0)
    {
        return;
    }
    __block NSString *uploadParamString = @"[";
    for(workSet *toUploadWorkset in toUploadWorksetArray)
    {
        if([toUploadWorkset isDeleted]){
            AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
            
            manager.responseSerializer = [AFJSONResponseSerializer serializer];
            manager.requestSerializer = [AFHTTPRequestSerializer serializer];
            manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];
            
            NSString *deleteURL = [NSString stringWithFormat:ROOT_URL@"mobile/workset/delete?user=%@&id=%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"username"],[toUploadWorkset worksetID]];
            
            [manager POST:deleteURL parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
                NSLog(@"delete request response is %@",responseObject);
                [[currentWorkSetManager sharedInstance] confirmDeleteWorkSet:toUploadWorkset];
                
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                NSLog(@"delete request error is %@",error);
            }];
        } else {
            NSString *sqlitepath = [NSString stringWithFormat:@"workset\\\\%@\\\\%@.sqlite",[[NSUserDefaults standardUserDefaults] objectForKey:@"username"],[toUploadWorkset name]];
            NSString *perUploadWorksetString = [NSString stringWithFormat:@"{\"id\":\"%@\",\"name\":\"%@\",\"user\":\"%@\",,\"time_create\":\"%@\",\"time_update\":\"%@\",\"location_name\":\"%@\",\"isfinished\":\"%d\",\"isautosync\":\"%d\",\"islocationtracked\":\"%d\",\"isonlinelayerdisplayed\":\"%d\",\"path\":\"%@\",\"coordinate\":\"%@\",\"description\":\"%@\"},",[toUploadWorkset worksetID],[toUploadWorkset name],[[NSUserDefaults standardUserDefaults] valueForKey:@"username"],[self localDateToUploadDateString:[toUploadWorkset createTime]],[self localDateToUploadDateString:[toUploadWorkset updateTime]],[toUploadWorkset locationString],[toUploadWorkset isCompleted]?1:0,[toUploadWorkset isAutoSync]?1:0,[toUploadWorkset isTracking]?1:0,[toUploadWorkset isOnlineLayerDisplayed]?1:0,sqlitepath,[NSString stringWithFormat:@"%ld,%ld",(long)[toUploadWorkset x],(long)[toUploadWorkset y]],[toUploadWorkset worksetDescription]];
            uploadParamString = [uploadParamString stringByAppendingString:perUploadWorksetString];
            
        }
    }
    if([uploadParamString isEqualToString:@"["])
    {
        return;
    }
    uploadParamString = [uploadParamString substringWithRange:NSMakeRange(0, [uploadParamString length] - 1)];
    uploadParamString = [uploadParamString stringByAppendingString:@"]"];
    
    [_uploadDBInfoManager POST:[ROOT_URL@"mobile/workset/form/uploadfile?username=" stringByAppendingString:[[NSUserDefaults standardUserDefaults] objectForKey:@"username"]] parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        
        [formData appendPartWithFormData:[uploadParamString dataUsingEncoding:NSUTF8StringEncoding] name:@"value"];
        NSString* appDocumentPath = [NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        for(workSet *perWorkset in toUploadWorksetArray)
        {
            NSString *worksetCDataDBName = [NSString stringWithFormat:@"%@.sqlite",[perWorkset name]];
            NSString* dbpath = [appDocumentPath stringByAppendingPathComponent:worksetCDataDBName];
            NSError *aerror;
            [formData appendPartWithFileURL:[NSURL fileURLWithPath:dbpath] name:@"files" error:&aerror];
            NSLog(@"app file eerror is %@",aerror);
        }
        
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"upload workset file response is %@",responseObject);
        
        NSString *requestTmp = [NSString stringWithString:operation.responseString];
        NSData *resData = [[NSData alloc] initWithData:[requestTmp dataUsingEncoding:NSUTF8StringEncoding]];
        NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:resData options:NSJSONReadingMutableLeaves error:nil];
        NSLog(@"%@",resultDic);
        //CFBooleanRef* success = [resultDic objectForKey:@"success"];
        NSNumber *number = [resultDic objectForKey:@"success"];
        NSLog(@"response result is %@,%d",[resultDic objectForKey:@"result"],[number intValue]);
        NSNumber *getLayernumber = [resultDic objectForKey:@"success"];
        
        BOOL isImageListEmpty = YES;
        for(workSet *toUploadWorkset in toUploadWorksetArray)
        {
            for(collectedData *cData in [toUploadWorkset collectedDataList]){
                if([[cData imageList] count] > 0){
                    isImageListEmpty = NO;
                }
            }
        }
        if(isImageListEmpty)
        {
            [self beginDownloadTask:toDownloadArray];
            return;
        }
        
        if([getLayernumber boolValue]){
            
            AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
            
            manager.responseSerializer = [AFHTTPResponseSerializer serializer];
            manager.requestSerializer = [AFHTTPRequestSerializer serializer];
            manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];
            [manager.requestSerializer setValue:@"multipart/form-data" forHTTPHeaderField:@"Content-Type"];
            
            [_uploadMediaManager POST:[ROOT_URL@"mobile/workset/multi/uploadfile?username=" stringByAppendingString:[[NSUserDefaults standardUserDefaults] objectForKey:@"username"]] parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
                NSError *error;
                NSString *uploadImageParamString = @"[";
                for(workSet *toUploadWorkset in toUploadWorksetArray)
                {
                    for(collectedData *cData in [toUploadWorkset collectedDataList]){
                        if([[cData imageList] count] > 0){
                            for(NSString *imageName in [cData imageNameList]){
                                NSString *realImageName = [imageName substringFromIndex:1];
                                NSString *perUploadImageParamString = [NSString stringWithFormat:@"{\"id\":\"%@\",\"name\":\"%@\",\"media\":\"%@\"},",[toUploadWorkset worksetID],[toUploadWorkset name],realImageName];
                                uploadImageParamString = [uploadImageParamString stringByAppendingString:perUploadImageParamString];
                                
                            }
                        }
                    }
                }
                NSString* appDocumentPath = [NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
                uploadImageParamString = [uploadImageParamString substringWithRange:NSMakeRange(0, [uploadImageParamString length] - 1)];
                uploadImageParamString = [uploadImageParamString stringByAppendingString:@"]"];
                [formData appendPartWithFormData:[uploadImageParamString dataUsingEncoding:NSUTF8StringEncoding] name:@"value"];
                for(workSet *toUploadWorkset in toUploadWorksetArray)
                {
                    for(collectedData *cData in [toUploadWorkset collectedDataList]){
                        if([[cData imageList] count] > 0){
                            for(NSString *imageName in [cData imageNameList]){
                                [formData appendPartWithFileURL:[NSURL fileURLWithPath:[appDocumentPath stringByAppendingPathComponent:imageName]] name:@"files" fileName:imageName mimeType:@"imag/jpeg" error:&error];
                            }
                        }
                    }
                }
            } success:^(AFHTTPRequestOperation *operation, id responseObject) {
                NSLog(@"upload workset image response is %@",responseObject);
                
                [self beginDownloadTask:toDownloadArray];
                
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                NSLog(@"upload workset image  error is %@",error);
                [SVProgressHUD dismiss];
                [SVProgressHUD showErrorWithStatus:@"获取信息失败，请检查网络连接"];
            }];
            
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"upload workset file  error is %@",error);
        [SVProgressHUD dismiss];
        [SVProgressHUD showErrorWithStatus:@"获取信息失败，请检查网络连接"];
        
    }];
}

-(void)beginDownloadTask:(NSArray*)toDownloadArray
{
    for(WorksetModel *toDownloadWorkset in toDownloadArray)
    {
        if(![toDownloadWorkset path] || [[toDownloadWorkset path] isEqualToString:@""]){
            NSLog(@"ERROR: no sqlite file relPath fournd for workset name :%@",[toDownloadWorkset name]);
        } else {
            NSDictionary *getLatestWorksetDataParam = @{@"user":[[NSUserDefaults standardUserDefaults] objectForKey:@"username"],@"fileType":@"worksetdb",@"relPath":[toDownloadWorkset path]};
            
            AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
            
            manager.responseSerializer = [AFHTTPResponseSerializer serializer];
            manager.requestSerializer = [AFJSONRequestSerializer serializer];
            [manager.requestSerializer setValue:@"application/json;charset=utf-8" forHTTPHeaderField:@"Content-Type"];
            
            NSLog(@"%@",[manager.requestSerializer valueForHTTPHeaderField:@"Content-Type"]);
            
            [_downloadDBInfoManager POST:ROOT_URL@"mobile/workset/download/file" parameters:getLatestWorksetDataParam success:^(AFHTTPRequestOperation *operation, id responseObject) {
                NSLog(@"download success");
                
                int err;
                sqlite3 *db;
                FMDatabase *fmdb;
                NSString *appDocumentPath = [NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
                NSString* dbpath = [appDocumentPath stringByAppendingPathComponent:@"workset.sqlite"];
                
                err = sqlite3_open_v2([dbpath UTF8String], &db, SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, NULL);
                sqlite3_enable_load_extension(db, 1);
                
                fmdb = [FMDatabase databaseWithPath:dbpath];
                [fmdb setDB:db :dbpath];
                
                [fmdb executeUpdate:DATABASECMD_INSERT_NEW_WORKSET,[toDownloadWorkset id],[toDownloadWorkset name],(NSString*)[[NSUserDefaults standardUserDefaults] objectForKey:@"username"], nil, [toDownloadWorkset time_create], [toDownloadWorkset time_update],[toDownloadWorkset location_name], @"", @"", [NSNumber numberWithBool:false], [NSNumber numberWithBool:false], [NSNumber numberWithBool:false],[NSNumber numberWithBool:false]];
                
                NSString *filePath = [NSString stringWithFormat:@"%@/%@.sqlite",appDocumentPath,[toDownloadWorkset name]];
                NSError *createFileError;
                [((NSData*)responseObject) writeToFile:filePath options:NSDataWritingAtomic error:&createFileError];
                
                NSLog(@"create file error is %@",createFileError);
                
                NSLog(@"response object is %@",operation);
                
                FMDatabase *downloadDB = [FMDatabase databaseWithPath:filePath];
                [downloadDB open];
                
                FMResultSet *queryMediaTableResult = [downloadDB executeQuery:@"select * from sqlite_master where type = 'table' and name like '%_media'"];
                while([queryMediaTableResult next]){
                    NSString *tableName = [queryMediaTableResult stringForColumn:@"name"];
                    NSString *queryMediaString = [NSString stringWithFormat:@"SELECT * FROM '%@'",tableName];
                    FMResultSet *queryMediaResult = [downloadDB executeQuery:queryMediaString];
                    while([queryMediaResult next]){
                        NSString *mediaFileName = [queryMediaResult stringForColumn:@"media"];
                        
                        NSString *downloadURL = [ROOT_URL@"mobile/workset/multi/download?" stringByAppendingFormat:@"username=%@&media=%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"username"],mediaFileName];
                        
                        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
                        
                        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
                        manager.requestSerializer = [AFJSONRequestSerializer serializer];
                        [manager.requestSerializer setValue:@"application/json;charset=utf-8" forHTTPHeaderField:@"Content-Type"];
                        
                        NSLog(@"%@",[manager.requestSerializer valueForHTTPHeaderField:@"Content-Type"]);
                        
                        [_downloadMediaManager POST:downloadURL parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
                            NSString *filePath = [NSString stringWithFormat:@"%@/%@",appDocumentPath,mediaFileName];
                            NSError *createFileError;
                            [((NSData*)responseObject) writeToFile:filePath options:NSDataWritingAtomic error:&createFileError];
                            
                            NSLog(@"create media file error is %@",createFileError);
                        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                            NSLog(@"download media error is %@",error);
                        }];
                    }
                    [queryMediaResult close];

                }
                [queryMediaTableResult close];
                [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshTaskCollectionTableView" object:nil];
                
                
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                NSLog(@"download error is %@",error);
                [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshTaskCollectionTableView" object:nil];
                
            }];

        }
    }
}

-(void)addNewSingleWorksetSyncTask:(workSet*)toSyncWorkset
{
    dispatch_sync(_queue, ^{
        NSString *sqlitepath = [NSString stringWithFormat:@"workset\\\\%@\\\\%@.sqlite",[[NSUserDefaults standardUserDefaults] objectForKey:@"username"],[toSyncWorkset name]];
        NSString *perUploadWorksetString = [NSString stringWithFormat:@"[{\"id\":\"%@\",\"name\":\"%@\",\"user\":\"%@\",,\"time_create\":\"%@\",\"time_update\":\"%@\",\"location_name\":\"%@\",\"isfinished\":\"%d\",\"isautosync\":\"%d\",\"islocationtracked\":\"%d\",\"isonlinelayerdisplayed\":\"%d\",\"path\":\"%@\",\"coordinate\":\"%@\",\"description\":\"%@\"}]",[toSyncWorkset worksetID],[toSyncWorkset name],[[NSUserDefaults standardUserDefaults] valueForKey:@"username"],[self localDateToUploadDateString:[toSyncWorkset createTime]],[self localDateToUploadDateString:[toSyncWorkset updateTime]],[toSyncWorkset locationString],[toSyncWorkset isCompleted]?1:0,[toSyncWorkset isAutoSync]?1:0,[toSyncWorkset isTracking]?1:0,[toSyncWorkset isOnlineLayerDisplayed]?1:0,sqlitepath,[NSString stringWithFormat:@"%ld,%ld",(long)[toSyncWorkset x],(long)[toSyncWorkset y]],[toSyncWorkset worksetDescription]];
        
        [_uploadDBInfoManager POST:[ROOT_URL@"mobile/workset/form/uploadfile?username=" stringByAppendingString:[[NSUserDefaults standardUserDefaults] objectForKey:@"username"]] parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
            
            [formData appendPartWithFormData:[perUploadWorksetString dataUsingEncoding:NSUTF8StringEncoding] name:@"value"];
            NSString* appDocumentPath = [NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
            
            NSString *worksetCDataDBName = [NSString stringWithFormat:@"%@.sqlite",[toSyncWorkset name]];
            NSString* dbpath = [appDocumentPath stringByAppendingPathComponent:worksetCDataDBName];
            NSError *aerror;
            [formData appendPartWithFileURL:[NSURL fileURLWithPath:dbpath] name:@"files" error:&aerror];
            NSLog(@"app file eerror is %@",aerror);
            
        } success:^(AFHTTPRequestOperation *operation, id responseObject) {
            [_uploadMediaManager POST:[ROOT_URL@"mobile/workset/multi/uploadfile?username=" stringByAppendingString:[[NSUserDefaults standardUserDefaults] objectForKey:@"username"]] parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
                NSError *error;
                NSString *uploadImageParamString = @"[";
                
                for(collectedData *cData in [toSyncWorkset collectedDataList]){
                    if([[cData imageList] count] > 0){
                        for(NSString *imageName in [cData imageNameList]){
                            NSString *realImageName = [imageName substringFromIndex:1];
                            NSString *perUploadImageParamString = [NSString stringWithFormat:@"{\"id\":\"%@\",\"name\":\"%@\",\"media\":\"%@\"},",[toSyncWorkset worksetID],[toSyncWorkset name],realImageName];
                            uploadImageParamString = [uploadImageParamString stringByAppendingString:perUploadImageParamString];
                            
                        }
                    }
                }
                
                NSString* appDocumentPath = [NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
                uploadImageParamString = [uploadImageParamString substringWithRange:NSMakeRange(0, [uploadImageParamString length] - 1)];
                uploadImageParamString = [uploadImageParamString stringByAppendingString:@"]"];
                [formData appendPartWithFormData:[uploadImageParamString dataUsingEncoding:NSUTF8StringEncoding] name:@"value"];
                
                for(collectedData *cData in [toSyncWorkset collectedDataList]){
                    if([[cData imageList] count] > 0){
                        for(NSString *imageName in [cData imageNameList]){
                            [formData appendPartWithFileURL:[NSURL fileURLWithPath:[appDocumentPath stringByAppendingPathComponent:imageName]] name:@"files" fileName:imageName mimeType:@"imag/jpeg" error:&error];
                        }
                    }
                }
                
            } success:^(AFHTTPRequestOperation *operation, id responseObject) {
                
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                
            }];
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            
        }];

    });
}


- (void)uploadSingleWorkset:(workSet*)toUploadWorkset totalSyncNumber:(NSInteger)totalCount currentSyncCount:(NSInteger)currentCount
{
    workSet *currentWorkset = toUploadWorkset;
    
    NSString* appDocumentPath = [NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    
    NSString *sqlitepath = [NSString stringWithFormat:@"workset\\\\%@\\\\%@.sqlite",[[NSUserDefaults standardUserDefaults] objectForKey:@"username"],[currentWorkset name]];
    
    NSString *paramString = [NSString stringWithFormat:@"[{\"id\":\"%@\",\"name\":\"%@\",\"user\":\"%@\",\"time_create\":\"%@\",\"time_update\":\"%@\",\"location_name\":\"%@\",\"path\":\"%@\"}]",[currentWorkset worksetID],[currentWorkset name],[currentWorkset creator],[self localDateToUploadDateString:[currentWorkset createTime]],[self localDateToUploadDateString:[currentWorkset updateTime]],[currentWorkset locationString],sqlitepath];
    
    NSLog(@"paramstring is %@",paramString);
    
    if([toUploadWorkset isDeleted]){
        

        
        
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        
        manager.responseSerializer = [AFJSONResponseSerializer serializer];
        manager.requestSerializer = [AFHTTPRequestSerializer serializer];
        manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];
        
        NSString *deleteURL = [NSString stringWithFormat:ROOT_URL@"mobile/workset/delete?user=%@&id=%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"username"],[currentWorkset worksetID]];
        
        //NSString *deleteURL = [NSString stringWithFormat:@"http://10.32.26.212:8080/slxc.server/mobile/workset/delete?user=wolf&id=047fe403-a31d-4591-ba10-26bd5a1b50b8"];
        
        [manager POST:deleteURL parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSLog(@"delete request response is %@",responseObject);
            NSInteger index = 0;
            for(WorksetModel* wModel in _laytestWorksetJsonObjectArray)
            {
                if([[wModel id] isEqualToString:[currentWorkset worksetID]])
                {
                    index = [_laytestWorksetJsonObjectArray indexOfObject:wModel];
                    
                }
            }
            [_laytestWorksetJsonObjectArray removeObjectAtIndex:index];
            [[currentWorkSetManager sharedInstance] confirmDeleteWorkSet:currentWorkset];
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"delete request error is %@",error);
        }];

        return;
    }
    
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    //manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];
    [manager.requestSerializer setValue:@"multipart/form-data" forHTTPHeaderField:@"Content-Type"];
    
    NSLog(@"%@",[manager.requestSerializer valueForHTTPHeaderField:@"Content-Type"]);

    [_uploadDBInfoManager POST:[ROOT_URL@"mobile/workset/form/uploadfile?username=" stringByAppendingString:[[NSUserDefaults standardUserDefaults] objectForKey:@"username"]] parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        
        [formData appendPartWithFormData:[paramString dataUsingEncoding:NSUTF8StringEncoding] name:@"value"];
        //NSString* dbpath = [appDocumentPath stringByAppendingPathComponent:@"workset.sqlite"];
        NSString *worksetCDataDBName = [NSString stringWithFormat:@"%@.sqlite",[currentWorkset name]];
        NSString* dbpath = [appDocumentPath stringByAppendingPathComponent:worksetCDataDBName];
        NSError *aerror;
        [formData appendPartWithFileURL:[NSURL fileURLWithPath:dbpath] name:@"files" error:&aerror];
        NSLog(@"app file eerror is %@",aerror);
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"response is %@",responseObject);
        
        NSString *requestTmp = [NSString stringWithString:operation.responseString];
        NSData *resData = [[NSData alloc] initWithData:[requestTmp dataUsingEncoding:NSUTF8StringEncoding]];
        NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:resData options:NSJSONReadingMutableLeaves error:nil];
        NSLog(@"%@",resultDic);
        //CFBooleanRef* success = [resultDic objectForKey:@"success"];
        NSNumber *number = [resultDic objectForKey:@"success"];
        NSLog(@"response result is %@,%d",[resultDic objectForKey:@"result"],[number intValue]);
        
        __block NSString *paramString = @"[";
        
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        
        manager.responseSerializer = [AFJSONResponseSerializer serializer];
        manager.requestSerializer = [AFJSONRequestSerializer serializer];
        manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];
        [manager.requestSerializer setValue:@"multipart/form-data" forHTTPHeaderField:@"Content-Type"];
        
        [_uploadMediaManager POST:[ROOT_URL@"mobile/workset/multi/uploadfile?username=" stringByAppendingString:[[NSUserDefaults standardUserDefaults] objectForKey:@"username"]] parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
            NSError *error;
            NSString *uploadImageParamString = @"[";
            for(collectedData *cData in [currentWorkset collectedDataList]){
                if([[cData imageList] count] > 0){
                    for(NSString *imageName in [cData imageNameList]){
                        NSString *perUploadImageParamString = [NSString stringWithFormat:@"{\"id\":\"%@\",\"name\":\"%@\",\"media\":\"%@\"},",[currentWorkset worksetID],[currentWorkset name],[imageName substringWithRange:NSMakeRange(1, [imageName length])]];
                        uploadImageParamString = [uploadImageParamString stringByAppendingString:perUploadImageParamString];
                        
                        //[formData appendPartWithFormData:[uploadImageParamString dataUsingEncoding:NSUTF8StringEncoding] name:@"value"];

                        //[formData appendPartWithFileURL:[NSURL fileURLWithPath:[appDocumentPath stringByAppendingPathComponent:imageName]] name:@"files" fileName:imageName mimeType:@"imag/jpeg" error:&error];
                    }
                }
            }
            uploadImageParamString = [uploadImageParamString substringWithRange:NSMakeRange(0, [uploadImageParamString length] - 1)];
            uploadImageParamString = [uploadImageParamString stringByAppendingString:@"]"];
            [formData appendPartWithFormData:[uploadImageParamString dataUsingEncoding:NSUTF8StringEncoding] name:@"value"];
            
            for(collectedData *cData in [currentWorkset collectedDataList]){
                if([[cData imageList] count] > 0){
                    for(NSString *imageName in [cData imageNameList]){
                        [formData appendPartWithFileURL:[NSURL fileURLWithPath:[appDocumentPath stringByAppendingPathComponent:imageName]] name:@"files" fileName:imageName mimeType:@"imag/jpeg" error:&error];
                    }
                }
            }
            
            //NSString *uploadImageParamString = [NSString stringWithFormat:@"[{\"id\":\"%@\",\"name\":\"%@\",\"media\":\"%@\"}]",[currentWorkset worksetID],[currentWorkset name],[currentWorkset creator],[self localDateToUploadDateString:[currentWorkset createTime]],[self localDateToUploadDateString:[currentWorkset updateTime]],[currentWorkset locationString],sqlitepath];
            
            
            /*
            [formData appendPartWithFormData:[uploadImageParamString dataUsingEncoding:NSUTF8StringEncoding] name:@"value"];
            //NSString* dbpath = [appDocumentPath stringByAppendingPathComponent:@"workset.sqlite"];
            NSString *worksetCDataDBName = [NSString stringWithFormat:@"%@.sqlite",[currentWorkset name]];
            NSString* dbpath = [appDocumentPath stringByAppendingPathComponent:worksetCDataDBName];
            NSError *aerror;
            [formData appendPartWithFileURL:[NSURL fileURLWithPath:dbpath] name:@"files" error:&aerror];
            NSLog(@"app file eerror is %@",aerror);
             */
            
            /*
            for(collectedData *cData in [currentWorkset collectedDataList]){
                
                [formData appendPartWithFormData:[paramString dataUsingEncoding:NSUTF8StringEncoding] name:@"value"];
                
                if([[cData imageList] count] > 0){
                    for(NSString *imageName in [cData imageNameList]){
                        
                        paramString = [paramString stringByAppendingFormat:@"{\"id\":\"%@\",\"name\":\"%@\",\"media\":\"%@\"},",[currentWorkset worksetID],[currentWorkset name],imageName];
                    }

                    paramString = [paramString stringByAppendingString:@"]"];
                    [formData appendPartWithFormData:[paramString dataUsingEncoding:NSUTF8StringEncoding] name:@"value"];
                    for(NSString *imageName in [cData imageNameList]){
                        
                        [formData appendPartWithFileURL:[NSURL fileURLWithPath:[appDocumentPath stringByAppendingPathComponent:imageName]] name:@"files" fileName:imageName mimeType:@"imag/jpeg" error:&error];
                        
                        NSLog(@"pack image error is %@",error);
                    }
                }
            }*/
            
            
        } success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSLog(@"upload image response is %@",responseObject);
            
            
            //[SVProgressHUD dismiss];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"upload image error is %@",error);
            //[SVProgressHUD dismiss];
        }];
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"eror si %@",error);
        //[SVProgressHUD dismiss];
    }];
    
    
}

- (void)downloadSingleWorkset:(WorksetModel*)toDownloadWorksetModel totalSyncNumber:(NSInteger)totalCount currentSyncCount:(NSInteger)currentCount
{
    if(![toDownloadWorksetModel path] || [[toDownloadWorksetModel path] isEqualToString:@""]){
        NSLog(@"ERROR: no sqlite file relPath fournd for workset name :%@",[toDownloadWorksetModel name]);
        return;
    }
    
    NSString* appDocumentPath = [NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    
    NSDictionary *getLatestWorksetDataParam = @{@"user":[[NSUserDefaults standardUserDefaults] objectForKey:@"username"],@"fileType":@"worksetdb",@"relPath":[toDownloadWorksetModel path]};
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    //manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/plain"];
    [manager.requestSerializer setValue:@"application/json;charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    
    NSLog(@"%@",[manager.requestSerializer valueForHTTPHeaderField:@"Content-Type"]);
    
    [_downloadDBInfoManager POST:@"http://218.94.6.92:8033/slxc.server/mobile/workset/download/file" parameters:getLatestWorksetDataParam success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"download success");
        
        int err;
        sqlite3 *db;
        FMDatabase *fmdb;
        NSString *appDocumentPath = [NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        NSString* dbpath = [appDocumentPath stringByAppendingPathComponent:@"workset.sqlite"];
        
        err = sqlite3_open_v2([dbpath UTF8String], &db, SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, NULL);
        sqlite3_enable_load_extension(db, 1);
        
        fmdb = [FMDatabase databaseWithPath:dbpath];
        [fmdb setDB:db :dbpath];
        
        [fmdb executeUpdate:DATABASECMD_INSERT_NEW_WORKSET,[toDownloadWorksetModel id],[toDownloadWorksetModel name],(NSString*)[[NSUserDefaults standardUserDefaults] objectForKey:@"username"], nil, [toDownloadWorksetModel time_create], [toDownloadWorksetModel time_update],[toDownloadWorksetModel location_name], @"", @"", [NSNumber numberWithBool:false], [NSNumber numberWithBool:false], [NSNumber numberWithBool:false],[NSNumber numberWithBool:false]];
        
        NSString *filePath = [NSString stringWithFormat:@"%@/%@.sqlite",appDocumentPath,[toDownloadWorksetModel name]];
        NSError *createFileError;
        [((NSData*)responseObject) writeToFile:filePath options:NSDataWritingAtomic error:&createFileError];
        
        NSLog(@"create file error is %@",createFileError);
        
        NSLog(@"response object is %@",operation);
        
        FMDatabase *downloadDB = [FMDatabase databaseWithPath:filePath];
        [downloadDB open];
        
        FMResultSet *queryMediaTableResult = [downloadDB executeQuery:@"select * from sqlite_master where type = 'table' and name like '%_media'"];
        while([queryMediaTableResult next]){
            NSString *tableName = [queryMediaTableResult stringForColumn:@"name"];
            NSString *queryMediaString = [NSString stringWithFormat:@"SELECT * FROM '%@'",tableName];
            FMResultSet *queryMediaResult = [downloadDB executeQuery:queryMediaString];
            while([queryMediaResult next]){
                NSString *mediaFileName = [queryMediaResult stringForColumn:@"media"];
                
                NSString *downloadURL = [@"http://218.94.6.92:8033/slxc.server/mobile/workset/multi/download?" stringByAppendingFormat:@"username=%@&media=%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"username"],mediaFileName];
                
                AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
                
                manager.responseSerializer = [AFHTTPResponseSerializer serializer];
                manager.requestSerializer = [AFJSONRequestSerializer serializer];
                //manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/plain"];
                [manager.requestSerializer setValue:@"application/json;charset=utf-8" forHTTPHeaderField:@"Content-Type"];
                
                NSLog(@"%@",[manager.requestSerializer valueForHTTPHeaderField:@"Content-Type"]);
                
                [_downloadMediaManager POST:downloadURL parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
                    NSString *filePath = [NSString stringWithFormat:@"%@/%@",appDocumentPath,mediaFileName];
                    NSError *createFileError;
                    [((NSData*)responseObject) writeToFile:filePath options:NSDataWritingAtomic error:&createFileError];
                    
                    NSLog(@"create media file error is %@",createFileError);
                } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                    NSLog(@"download media error is %@",error);
                }];
            }
            [queryMediaResult close];
            
            if(totalCount != 0 && totalCount == currentCount){
                //[SVProgressHUD dismiss];
            }
        }
        [queryMediaTableResult close];
        
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"download error is %@",error);
        if(totalCount != 0 && totalCount == currentCount){
            //[SVProgressHUD dismiss];
        }
        
    }];
}

- (void)syncAllWorksets
{
    __block NSInteger syncCount = 0;
    
    [SVProgressHUD showWithStatus:@"获取服务器信息中..." maskType:SVProgressHUDMaskTypeBlack];
    
    [_laytestWorksetJsonObjectArray removeAllObjects];
    _laytestWorksetJsonObjectArray= [[NSMutableArray alloc] initWithCapacity:10];
    
    
    
    __block NSMutableArray *uploadOperationArray = [[NSMutableArray alloc] initWithCapacity:10];
    __block NSMutableArray *downloadOperationArray = [[NSMutableArray alloc] initWithCapacity:10];
    
    NSDictionary *getLatestWorksetListParam = @{@"user":[[NSUserDefaults standardUserDefaults] objectForKey:@"username"]};
    
    AFHTTPRequestOperationManager *worksetListRequestManager = [AFHTTPRequestOperationManager manager];
    worksetListRequestManager.responseSerializer = [AFJSONResponseSerializer serializer];
    worksetListRequestManager.requestSerializer = [AFJSONRequestSerializer serializer];
    
    
    [worksetListRequestManager GET:@"http://218.94.6.92:8033/slxc.server/mobile/workset/getList" parameters:getLatestWorksetListParam success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"get workset list response is %@",responseObject);
        
        NSString *requestTmp = [NSString stringWithString:operation.responseString];
        NSData *resData = [[NSData alloc] initWithData:[requestTmp dataUsingEncoding:NSUTF8StringEncoding]];
        NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:resData options:NSJSONReadingMutableLeaves error:nil];
        
        NSNumber *getLayernumber = [resultDic objectForKey:@"success"];
        
        if([getLayernumber boolValue]){
            
            NSArray *latestWorksetArray = [resultDic objectForKey:@"result"];
            for(NSDictionary *dict in latestWorksetArray){
                NSError *error;
                WorksetModel *latestWorksetModel = [[WorksetModel alloc] initWithDictionary:dict error:&error];
                
                NSLog(@"json parse error is %@",error);
                [_laytestWorksetJsonObjectArray addObject:latestWorksetModel];
            }
            
            /*STEP 1. Check if new added or updated worksets need to upload*/
            
            NSString *notiString = [NSString stringWithFormat:@"正在上传工作集..."];
            [SVProgressHUD setStatus:notiString];
            
            for(workSet *localWorkset in [[currentWorkSetManager sharedInstance] getWorksetArray]){
                BOOL needUpdate = YES;
                for(WorksetModel *workset in _laytestWorksetJsonObjectArray){
                    if([[localWorkset name] isEqualToString:[workset name]]){
                        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
                        [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
                        NSDateFormatter *remoteDateFormatter = [[NSDateFormatter alloc] init];
                        [remoteDateFormatter setDateFormat:@"yyyyMMddHHmmss"];
                        NSDate *localUpdateDate = [dateFormatter dateFromString:[localWorkset updateTime]];
                        NSDate *remoteUpdateDate = [remoteDateFormatter dateFromString:[workset time_update]];
                        if([localUpdateDate isEqualToDate:remoteUpdateDate] || [[remoteUpdateDate laterDate:localUpdateDate] isEqualToDate:remoteUpdateDate]){
                            if(![localWorkset isDeleted]){
                                needUpdate = NO;
                            }
                        }
                    }
                }
                if(needUpdate){
                    
                    [self uploadSingleWorkset:localWorkset totalSyncNumber:0 currentSyncCount:0];
                } else {
                    [SVProgressHUD setStatus:@"正在下载工作集..."];
                }
            }
            
            [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(checkingUploadOperationAllFinished:) userInfo:_laytestWorksetJsonObjectArray repeats:YES];
            
            /*STEP 2. Check if new added or updated worksets need to download*/
            /*
            for(WorksetModel *workset in laytestWorksetJsonObjectArray){
                BOOL needUpdate = YES;
                for(workSet *localWorkset in [[currentWorkSetManager sharedInstance] getWorksetArray]){
                    if([[localWorkset name] isEqualToString:[workset name]]){
                        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
                        [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
                        NSDateFormatter *remoteDateFormatter = [[NSDateFormatter alloc] init];
                        [remoteDateFormatter setDateFormat:@"yyyyMMddHHmmss"];
                        NSDate *localUpdateDate = [dateFormatter dateFromString:[localWorkset updateTime]];
                        NSDate *remoteUpdateDate = [remoteDateFormatter dateFromString:[workset time_update]];
                        if([localUpdateDate isEqualToDate:remoteUpdateDate] || [[remoteUpdateDate laterDate:localUpdateDate] isEqualToDate:localUpdateDate]){
                            needUpdate = NO;
                            continue;
                        }
                    }
                    
                }
                if(needUpdate){
                    [worksetToDownloadArray addObject:[workset copy]];
                }
            }
            if([worksetToDownloadArray count] == 0){
                [SVProgressHUD dismiss];
                [SVProgressHUD showInfoWithStatus:@"同步完成"];
                
                
            } else {
                
                NSInteger currentCount = 0;
                for(WorksetModel *wModel in worksetToDownloadArray){
                    currentCount++;
                    [self downloadSingleWorkset:wModel totalSyncNumber:[worksetToDownloadArray count] currentSyncCount:currentCount];
                }
                
            }
             */
            
            
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"get workset list error is %@",error);
        [SVProgressHUD dismiss];
        [SVProgressHUD showErrorWithStatus:@"获取信息失败，请检查网络连接"];
    }];
    
    
}

-(void)beginDownloadingToSyncOperations: (NSMutableArray*)laytestWorksetJsonObjectArray
{
    __block NSMutableArray *worksetToDownloadArray = [[NSMutableArray alloc] initWithCapacity:10];
    for(WorksetModel *workset in laytestWorksetJsonObjectArray){
        BOOL needUpdate = YES;
        for(workSet *localWorkset in [[currentWorkSetManager sharedInstance] getWorksetArray]){
            if([[localWorkset name] isEqualToString:[workset name]]){
                NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
                [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
                NSDateFormatter *remoteDateFormatter = [[NSDateFormatter alloc] init];
                [remoteDateFormatter setDateFormat:@"yyyyMMddHHmmss"];
                NSDate *localUpdateDate = [dateFormatter dateFromString:[localWorkset updateTime]];
                NSDate *remoteUpdateDate = [remoteDateFormatter dateFromString:[workset time_update]];
                if([localUpdateDate isEqualToDate:remoteUpdateDate] || [[remoteUpdateDate laterDate:localUpdateDate] isEqualToDate:localUpdateDate]){
                    needUpdate = NO;
                    continue;
                }
            }
            
        }
        if(needUpdate){
            [worksetToDownloadArray addObject:[workset copy]];
        }
    }
    if([worksetToDownloadArray count] == 0){
        [SVProgressHUD dismiss];
        [SVProgressHUD showInfoWithStatus:@"同步完成"];
        
        
    } else {
        
        NSInteger currentCount = 0;
        for(WorksetModel *wModel in worksetToDownloadArray){
            currentCount++;
            [self downloadSingleWorkset:wModel totalSyncNumber:[worksetToDownloadArray count] currentSyncCount:currentCount];
        }
        [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(checkingDownloadOperationAllFinished:) userInfo:laytestWorksetJsonObjectArray repeats:YES];
        
    }

}

-(void)newCheckingAllOperationFinished:(NSTimer *)timer
{
    BOOL isAllFinished = YES;
    for(NSOperation *operation in [[_uploadMediaManager operationQueue] operations])
    {
        if(![operation isFinished])
        {
            isAllFinished = NO;
        }
    }
    for(NSOperation *operation in [[_uploadDBInfoManager operationQueue] operations])
    {
        if(![operation isFinished])
        {
            isAllFinished = NO;
        }
    }
    for(NSOperation *operation in [[_downloadMediaManager operationQueue] operations])
    {
        if(![operation isFinished])
        {
            isAllFinished = NO;
        }
    }
    for(NSOperation *operation in [[_downloadDBInfoManager operationQueue] operations])
    {
        if(![operation isFinished])
        {
            isAllFinished = NO;
        }
    }
    if(isAllFinished)
    {
        
        [timer invalidate];
        
        [[currentWorkSetManager sharedInstance] reloadWorksetInfo];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshTaskCollectionTableView" object:nil];
        [SVProgressHUD dismiss];
        [SVProgressHUD showInfoWithStatus:@"同步完成"];
    }
    
}

-(void)checkingDownloadOperationAllFinished:(NSTimer *)timer
{
    if([[_downloadMediaManager operationQueue] operationCount] == 0 && [[_downloadDBInfoManager operationQueue] operationCount] == 0){
        
        [SVProgressHUD dismiss];
        [timer invalidate];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshTaskCollectionTableView" object:nil];
        
    }
}

-(void)checkingUploadOperationAllFinished:(NSTimer *)timer
{
    NSLog(@"operations number is %d",[[_uploadMediaManager operationQueue] operationCount]);
    if([[_uploadMediaManager operationQueue] operationCount] == 0){
        
        [self beginDownloadingToSyncOperations:[timer userInfo]];
        [timer invalidate];

    } else {
        BOOL allFinished = YES;
        for(NSOperation *operation in [[_uploadMediaManager operationQueue] operations]){
            if(![operation isFinished]){
                allFinished = NO;
            }
        }
        if(allFinished){
            [self beginDownloadingToSyncOperations:[timer userInfo]];
            [timer invalidate];
        }
    }
    
}

- (void)syncSingleWorkset:(workSet*)toSyncWorkset totalSyncNumber:(NSInteger)totalCount currentSyncCount:(NSInteger)currentCount
{
    __block NSMutableArray *laytestWorksetJsonObjectArray = [[NSMutableArray alloc] initWithCapacity:10];
    
    NSDictionary *getLatestWorksetListParam = @{@"user":[[NSUserDefaults standardUserDefaults] objectForKey:@"username"]};
    
    AFHTTPRequestOperationManager *worksetListRequestManager = [AFHTTPRequestOperationManager manager];
    worksetListRequestManager.responseSerializer = [AFJSONResponseSerializer serializer];
    worksetListRequestManager.requestSerializer = [AFJSONRequestSerializer serializer];
    
    
    [worksetListRequestManager GET:@"http://218.94.6.92:8033/slxc.server/mobile/workset/getList" parameters:getLatestWorksetListParam success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"get workset list response is %@",responseObject);
        
        NSString *requestTmp = [NSString stringWithString:operation.responseString];
        NSData *resData = [[NSData alloc] initWithData:[requestTmp dataUsingEncoding:NSUTF8StringEncoding]];
        NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:resData options:NSJSONReadingMutableLeaves error:nil];
        
        NSNumber *getLayernumber = [resultDic objectForKey:@"success"];
        
        if([getLayernumber boolValue]){
            
            NSArray *latestWorksetArray = [resultDic objectForKey:@"result"];
            for(NSDictionary *dict in latestWorksetArray){
                NSError *error;
                WorksetModel *latestWorksetModel = [[WorksetModel alloc] initWithDictionary:dict error:&error];
                
                NSLog(@"json parse error is %@",error);
                [laytestWorksetJsonObjectArray addObject:latestWorksetModel];
            }
            
            /*STEP 1. Check if new added or updated worksets need to download*/
            
            BOOL needUpdate = YES;
            
            for(WorksetModel *workset in laytestWorksetJsonObjectArray){
                if([[toSyncWorkset name] isEqualToString:[workset name]]){
                    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
                    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
                    NSDateFormatter *remoteDateFormatter = [[NSDateFormatter alloc] init];
                    [remoteDateFormatter setDateFormat:@"yyyyMMddHHmmss"];
                    NSDate *localUpdateDate = [dateFormatter dateFromString:[toSyncWorkset updateTime]];
                    NSDate *remoteUpdateDate = [remoteDateFormatter dateFromString:[workset time_update]];
                    if([localUpdateDate isEqualToDate:remoteUpdateDate]){
                        needUpdate = NO;
                        break;
                    } else if([[localUpdateDate laterDate:remoteUpdateDate] isEqualToDate:localUpdateDate]){
                        break;
                    } else {
                        needUpdate = NO;
                        [self downloadSingleWorkset:workset totalSyncNumber:0 currentSyncCount:0];
                        break;
                        
                    }
                }
            }
            if(needUpdate){
                [self uploadSingleWorkset:toSyncWorkset totalSyncNumber:0 currentSyncCount:0];
            }
            
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"get workset list error is %@",error);
        [SVProgressHUD dismiss];
        [SVProgressHUD showErrorWithStatus:@"获取信息失败，请检查网络连接"];
    }];
    
}

- (void)beginScheduleSync
{
    
    [NSTimer scheduledTimerWithTimeInterval:300.0 target:self selector:@selector(unitScheduleSyncTask:) userInfo:nil repeats:YES];

}

-(void)unitScheduleSyncTask :(NSTimer*)timer
{
    if([[_uploadMediaManager operationQueue] operationCount] !=0 || [[_uploadDBInfoManager operationQueue] operationCount] !=0)
    {
        return;
    }
    [_autoSyncWorksetList removeAllObjects];
    for(workSet *tempWorkset in [[currentWorkSetManager sharedInstance] getWorksetArray])
    {
        if([tempWorkset isAutoSync])
        {
            [_autoSyncWorksetList addObject:tempWorkset];
        }
    }
    for (workSet *toSyncWorkset in _autoSyncWorksetList){
        [self uploadSingleWorkset:toSyncWorkset totalSyncNumber:0 currentSyncCount:0];
    }
}

@end
